package com.koc.robot;

import android.view.MotionEvent;

enum State
{
	STATE_INTRO,
	STATE_MENU,
	STATE_GAME,
	
	STATE_INVALID,
}

public class Scheduler
{	
	public static Scheduler instance()
	{
		if (schedulerInstance == null)
		{
			schedulerInstance = new Scheduler();
		}
		
		return schedulerInstance;
	}
	
	public void tick(float dt)
	{		
		dt = Math.min(dt, 0.1666666667f);
		
		if (mCurState == null)
		{
			Global.initGlobal(Global.context);
			tostate(State.STATE_INTRO);
		}
		
		Global.creditss = Global.creditss + dt * 4.0f;
		Global.creditsr = (float)Math.sin(Global.creditss) / 10.0f;
		
		// tick the background blocks
		if (Global.backgroundblocks != null)
		{
			for (int i = 0; i < Global.backgroundblocks.length; i++)
			{
				Global.backgroundblocks[i].update(dt);
			}
		}
		
		Global.rainbowi = Global.rainbowi + dt * 0.2f;
		while (Global.rainbowi > 1.0f)
		{
			Global.rainbowi = Global.rainbowi - 1.0f;
		}
		
		// update fillcolor and outlinecolor
		Global.fillcolor = Global.getrainbowcolor(Global.rainbowi, 150.0f / 255.0f);
		Global.outlinecolor = Global.getrainbowcolor(Global.rainbowi, 80.0f / 255.0f);
		
		mCurState.update(dt); 
	}
	
	public void render()
	{
		// render the background blocks
		Global.blockVertexOffset = 0;
		
		if (mCurState.getStateTag() != State.STATE_INTRO)
		{
			if (Global.backgroundblocks != null)
			{
				for (int i = 0; i < Global.backgroundblocks.length; i++)
				{
					Global.backgroundblocks[i].draw();
				}
				
				Global.drawblock();
			}
		}
		
		mCurState.render();
	}
	
	public void tostate(State _state)
	{
		if (mCurState != null)
		{
			mCurState.unload();
		}
		
		switch (_state)
		{
		case STATE_MENU:
			mCurState = new MenuState(0, 0);
			break;
			
		case STATE_INTRO:
			mCurState = new IntroState();
			break;
			
		case STATE_GAME:
			mCurState = new GameState();
			break;
		default:
			break;
		}
		
		mCurState.load();
	}
	
	public void onTouched(MotionEvent e)
	{
		if(mCurState != null)
			mCurState.onTouched(e);
	}
	
	public void onButtonClicked(int buttonId)
	{
		if(mCurState != null)
			mCurState.onButtonClicked(buttonId);
	}
	
	private BasicState mCurState = null;
	private static Scheduler schedulerInstance = null;
}
